# -*- coding: utf-8 -*-
"""
配置管理模块
提供统一的配置加载、保存和管理接口，便于后续扩展
"""

import os
import json
from typing import Any, Dict, Optional, List


class ConfigManager:
    """配置管理器"""
    
    # 配置项默认值
    DEFAULTS = {
        'processes': [],  # 进程列表，格式：[{'name': 'xxx', 'type': 'name'/'pid'}]
        'interval': 60,  # 检查间隔（秒）
        'last_tab': 0,   # 最后选择的页签索引（0=通用, 1=任务, 2=截图, 3=守护, 4=端口vs进程）
        'hotkey_start': 'ctrl+alt+i',  # 开始截图快捷键
        'hotkey_full': 'ctrl+alt+shift+i',  # 全屏截图快捷键
        'screenshot_hide_main_window': True,  # 截图时隐藏主窗口到托盘
        'guardian_processes': [],  # 守护进程列表，格式：[{'path': 'xxx', 'args': 'xxx', 'interval': 60}]
        'guardian_interval': 60,  # 守护检查间隔（秒）
    }
    
    def __init__(self, config_file: str = "window_spy_config.json"):
        """
        初始化配置管理器
        
        Args:
            config_file: 配置文件路径
        """
        self.config_file = config_file
        self._config: Dict[str, Any] = {}
        self._load()
    
    def _load(self):
        """从文件加载配置"""
        self._config = self.DEFAULTS.copy()
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    file_config = json.load(f)
                    # 合并配置，保留默认值中没有的项
                    self._config.update(file_config)
                    # 只保留已知的配置项，过滤掉无效项
                    self._config = {k: v for k, v in self._config.items() if k in self.DEFAULTS}
        except Exception as e:
            # 加载失败时使用默认值
            print(f"加载配置失败: {e}, 使用默认配置")
            self._config = self.DEFAULTS.copy()
    
    def save(self):
        """保存配置到文件"""
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self._config, f, ensure_ascii=False, indent=2)
            print(f"[CONFIG] 配置已保存: {self.config_file}, last_tab={self._config.get('last_tab', 0)}")
            return True
        except Exception as e:
            print(f"保存配置失败: {e}")
            return False
    
    def get(self, key: str, default: Any = None) -> Any:
        """
        获取配置项
        
        Args:
            key: 配置项名称
            default: 默认值（如果未指定，使用DEFAULTS中的默认值）
        
        Returns:
            配置项的值
        """
        if default is None and key in self.DEFAULTS:
            default = self.DEFAULTS[key]
        return self._config.get(key, default)
    
    def set(self, key: str, value: Any):
        """
        设置配置项
        
        Args:
            key: 配置项名称
            value: 配置项的值
        
        Returns:
            是否设置成功
        """
        if key in self.DEFAULTS:
            self._config[key] = value
            return True
        return False
    
    def get_processes(self) -> List[Dict[str, str]]:
        """
        获取进程列表
        
        Returns:
            进程列表，格式：[{'name': 'xxx', 'type': 'name'/'pid'}]
        """
        processes = self.get('processes', [])
        result = []
        for item in processes:
            if isinstance(item, str):
                # 兼容旧格式：只有进程名
                result.append({'name': item, 'type': 'name'})
            elif isinstance(item, dict):
                # 新格式：包含类型
                result.append({
                    'name': item.get('name', ''),
                    'type': item.get('type', 'name')
                })
        return result
    
    def set_processes(self, processes: List[Dict[str, str]]):
        """
        设置进程列表
        
        Args:
            processes: 进程列表，格式：[{'name': 'xxx', 'type': 'name'/'pid'}]
        """
        self.set('processes', processes)
    
    def get_interval(self) -> int:
        """获取检查间隔（秒）"""
        return self.get('interval', 60)
    
    def set_interval(self, interval: int):
        """设置检查间隔（秒）"""
        if isinstance(interval, int) and interval > 0:
            self.set('interval', interval)
    
    def get_last_tab(self) -> int:
        """获取最后选择的页签索引"""
        tab = self.get('last_tab', 0)
        if isinstance(tab, int) and 0 <= tab < 5:
            return tab
        return 0

    def set_last_tab(self, tab_index: int):
        """设置最后选择的页签索引"""
        if isinstance(tab_index, int) and 0 <= tab_index < 5:
            self.set('last_tab', tab_index)
    
    def get_hotkey_start(self) -> str:
        """获取开始截图快捷键"""
        return self.get('hotkey_start', 'ctrl+alt+i')
    
    def set_hotkey_start(self, hotkey: str):
        """设置开始截图快捷键"""
        self.set('hotkey_start', hotkey)
    
    def get_hotkey_full(self) -> str:
        """获取全屏截图快捷键"""
        return self.get('hotkey_full', 'ctrl+alt+shift+i')
    
    def set_hotkey_full(self, hotkey: str):
        """设置全屏截图快捷键"""
        self.set('hotkey_full', hotkey)
    
    def get_screenshot_hide_main_window(self) -> bool:
        """获取截图时是否隐藏主窗口"""
        return self.get('screenshot_hide_main_window', True)
    
    def set_screenshot_hide_main_window(self, value: bool):
        """设置截图时是否隐藏主窗口"""
        self.set('screenshot_hide_main_window', bool(value))
    
    def get_guardian_processes(self) -> List[Dict[str, Any]]:
        """获取守护进程列表"""
        return self.get('guardian_processes', [])
    
    def set_guardian_processes(self, processes: List[Dict[str, Any]]):
        """设置守护进程列表"""
        self.set('guardian_processes', processes)
    
    def get_guardian_interval(self) -> int:
        """获取守护检查间隔（秒）"""
        return self.get('guardian_interval', 60)
    
    def set_guardian_interval(self, interval: int):
        """设置守护检查间隔（秒）"""
        if isinstance(interval, int) and interval > 0:
            self.set('guardian_interval', interval)
    
    def reset(self):
        """重置为默认配置"""
        self._config = self.DEFAULTS.copy()
    
    def to_dict(self) -> Dict[str, Any]:
        """获取所有配置的字典副本"""
        return self._config.copy()

